#!/bin/bash

# 检查root权限
if [ "$(id -u)" -ne 0 ]; then
  echo "此脚本需要root权限，请使用sudo执行"
  exit 1
fi

# 设置固定WiFi信息
SSID="wifiname"
PASSWORD="wifipassword"

# 清理函数：用于在脚本退出时清理临时文件
cleanup() {
    rm -f /tmp/auto_wifi_update_$$
    echo "清理完成"
}

trap cleanup EXIT

# 检查服务是否已存在并停止
if systemctl is-active --quiet auto_wifi.service; then
    echo "停止正在运行的auto_wifi服务..."
    systemctl stop auto_wifi.service
fi

# 检查服务是否已启用并禁用
if systemctl is-enabled --quiet auto_wifi.service 2>/dev/null; then
    echo "禁用auto_wifi服务..."
    systemctl disable auto_wifi.service
fi

# 备份旧的脚本文件（如果存在）
if [ -f /usr/local/bin/auto_wifi.sh ]; then
    BACKUP_FILE="/usr/local/bin/auto_wifi.sh.backup.$(date +%Y%m%d_%H%M%S)"
    echo "备份旧脚本: $BACKUP_FILE"
    cp /usr/local/bin/auto_wifi.sh "$BACKUP_FILE"
fi

# 创建自动连接脚本
echo "创建/更新自动连接脚本..."
cat > /usr/local/bin/auto_wifi.sh <<'EOF'
#!/bin/bash

# 函数：获取可用的WiFi接口
get_wifi_interface() {
    # 方法1：使用nmcli查找WiFi设备
    local wifi_iface=$(nmcli device status | awk '$2 == "wifi" && $3 == "disconnected" {print $1; exit}')
    
    if [ -n "$wifi_iface" ]; then
        echo "$wifi_iface"
        return 0
    fi
    
    # 方法2：使用ip命令查找无线接口
    wifi_iface=$(ip link show | awk -F': ' '/^[0-9]+: wl/ {print $2; exit}')
    
    if [ -n "$wifi_iface" ]; then
        echo "$wifi_iface"
        return 0
    fi
    
    # 方法3：使用iwconfig查找无线接口
    if command -v iwconfig &> /dev/null; then
        wifi_iface=$(iwconfig 2>/dev/null | grep -v "no wireless" | awk '!/^ / && /IEEE/ {print $1; exit}')
        if [ -n "$wifi_iface" ]; then
            echo "$wifi_iface"
            return 0
        fi
    fi
    
    echo ""
    return 1
}

# 等待网络服务就绪
sleep 10

# 获取WiFi接口
WIFI_INTERFACE=$(get_wifi_interface)

if [ -z "$WIFI_INTERFACE" ]; then
    echo "$(date): 未找到可用的WiFi接口" >> /var/log/auto_wifi.log
    exit 1
fi

echo "$(date): 使用WiFi接口: $WIFI_INTERFACE" >> /var/log/auto_wifi.log

# 检查接口状态
INTERFACE_STATE=$(nmcli -t -f DEVICE,STATE dev | grep "^$WIFI_INTERFACE:" | cut -d: -f2)

if [ "$INTERFACE_STATE" = "connected" ]; then
    echo "$(date): 接口 $WIFI_INTERFACE 已连接，跳过连接" >> /var/log/auto_wifi.log
    exit 0
fi

# 尝试连接WiFi
MAX_RETRIES=3
RETRY_COUNT=0

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    echo "$(date): 尝试连接WiFi (尝试 $((RETRY_COUNT+1))/$MAX_RETRIES)" >> /var/log/auto_wifi.log
    
    if nmcli dev wifi connect "TestOne" password "1234567890" ifname "$WIFI_INTERFACE"; then
        echo "$(date): 成功连接到WiFi" >> /var/log/auto_wifi.log
        exit 0
    fi
    
    RETRY_COUNT=$((RETRY_COUNT+1))
    sleep 5
done

echo "$(date): 连接WiFi失败，已达最大重试次数" >> /var/log/auto_wifi.log
exit 1
EOF

# 设置执行权限
chmod +x /usr/local/bin/auto_wifi.sh

# 创建或清空日志文件
echo "设置日志文件..."
touch /var/log/auto_wifi.log
chmod 644 /var/log/auto_wifi.log

# 备份旧的服务文件（如果存在）
if [ -f /etc/systemd/system/auto_wifi.service ]; then
    BACKUP_SERVICE="/etc/systemd/system/auto_wifi.service.backup.$(date +%Y%m%d_%H%M%S)"
    echo "备份旧服务文件: $BACKUP_SERVICE"
    cp /etc/systemd/system/auto_wifi.service "$BACKUP_SERVICE"
fi

# 创建systemd服务文件
echo "创建/更新systemd服务..."
cat > /etc/systemd/system/auto_wifi.service <<EOF
[Unit]
Description=Auto Connect WiFi
After=network.target
Wants=network.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/auto_wifi.sh
RemainAfterExit=yes
# 每30秒重试一次，最多重试3次
Restart=on-failure
RestartSec=30
StartLimitInterval=300
StartLimitBurst=3

[Install]
WantedBy=multi-user.target
EOF

# 重新加载systemd配置
echo "重新加载systemd配置..."
systemctl daemon-reload

# 启用并启动服务
echo "启用并启动服务..."
systemctl enable auto_wifi.service
systemctl start auto_wifi.service

# 显示配置结果
echo ""
echo "=== 配置完成 ==="
echo "服务状态："
systemctl status auto_wifi.service --no-pager -l

# 显示备份信息
if [ -n "$BACKUP_FILE" ] || [ -n "$BACKUP_SERVICE" ]; then
    echo ""
    echo "=== 备份文件 ==="
    [ -n "$BACKUP_FILE" ] && echo "脚本备份: $BACKUP_FILE"
    [ -n "$BACKUP_SERVICE" ] && echo "服务备份: $BACKUP_SERVICE"
fi

echo ""
echo "=== 使用说明 ==="
echo "查看实时日志: tail -f /var/log/auto_wifi.log"
echo "手动测试脚本: /usr/local/bin/auto_wifi.sh"
echo "重启服务: systemctl restart auto_wifi.service"
echo "禁用服务: systemctl disable --now auto_wifi.service"
echo ""
echo "建议重启系统验证自动连接功能"
